<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;
use App\Models\OpenapiLog;

class LmsService
{
    private $host;
    private $cache_prefix = 'lms_';
    public $response;

    public function __construct()
    {
        $this->host = config('app.lms_api_host');
        $this->response = Http::withHeaders($this->getHeaders());
    }

    public function pushClue($car_model, $series_name, $clue_id, $tel, $real_name, $dealer_id)
    {
        $data = [
            'clues' => [
                0 => [
                    'carModel' => $car_model,
                    'seriesName' => $series_name,
                    'clueId' => $clue_id,
                    'tel' => $tel,
                    'realName' => $real_name,
                    'dealerId' => $dealer_id,
                    'source' => 'eg'
                ]
            ]
        ];
        $url = $this->host . '/clue/receiveClues';
        $result = $this->response->post($url, $data)->json();
        OpenapiLog::addLog($url,$data,$result,'post');
        if(isset($result['code']) && $result['code'] == 200){
            return true;
        }else{
            return false;
        }
    }

    public function getHeaders()
    {
        $cache_key = $this->cache_prefix . 'sign';
        $result = Cache::remember($cache_key, 60, function () {
            $url = $this->host . '/clue/getSign';
            $result = Http::get($url)->json();
            OpenapiLog::addLog($url,null,$result,'get');
            if (isset($result['sign']) && isset($result['timestamp'])) {
                return $result;
            } else {
                throw_invalid_request_exception('lms-get-sign-fail', $result);
            }
        });
        return $result;
    }
}
